<?php
namespace common\services\IM\tengxun;

use common\models\Functions;
use linslin\yii2\curl\Curl;
use Yii;
/**
 * Created by PhpStorm.
 * User: songnaize
 * Date: 2021/6/7
 * Time: 8:35 PM
 */

class TxIm
{
    /**私有静态参数**/
    private $SDKAPPID = '';
    private $KEY = '';
    private $USER_ID = '';

    private $api = '';

    public function __construct() {
        $this->SDKAPPID = Yii::$app->params['TXIM_SDK_APPID'];
        $this->KEY = Yii::$app->params['TXIM_KEY'];
        $this->USER_ID = Yii::$app->params['TXIM_IDENTIFIER'];
    }

    /**
     * 添加用户
     * @param string $txCode
     * @param string $nickName
     * @param string $face
     * @return bool
     *
     */
    public function addUser($txCode = '',  $nickName = '', $face = '') {
        if (!$txCode || !$nickName || !$face) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 封装参数
        $data['Identifier'] = (string) $txCode;
        $data['Nick'] = $nickName;
        $data['FaceUrl'] = $face;

//        Yii::info(json_encode($data,true),'IM请求信息');
        //发送请求
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 更新用户信息
     * @param string $txCode
     * @param array $updateData
     * @return bool
     *
     */
    public function updateImUser($txCode = '', $updateData = []) {
        if (!$txCode || !$updateData) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 封装参数
        $data['From_Account'] = (string) $txCode;
        $data['ProfileItem'] = $updateData;

//        Yii::info(json_encode($data,true),'IM请求信息');
        //发送请求
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        var_dump($res);die;
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 校验黑名单关系
     * @param string $userTxCode
     * @param string $friendTxCode
     * @return bool
     *
     */
    public function checkBlack($userTxCode = '',  $friendTxCode = '') {
        if (!$userTxCode || !$friendTxCode) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/sns/black_list_check?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";


        // 封装参数
        $data = [
            'From_Account' => $userTxCode,   #需要校验该 UserID 的黑名单
            'To_Account' => [
                $friendTxCode,
            ],  # 待校验的黑名单的 UserID 列表，单次请求的 To_Account 数不得超过1000
            "CheckType" => "BlackCheckResult_Type_Single",   #校验模式   单向校验黑名单关系 BlackCheckResult_Type_Single   双向校验黑名单关系 BlackCheckResult_Type_Both
        ];

//        Yii::info(json_encode($data,true),'IM请求信息');
        //发送请求
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        $result = '';
        if (!empty($res['BlackListCheckItem'])) {
            $result = $res['BlackListCheckItem'][0]['Relation'] ?? [];
        }
        return $result;
    }

    /**
     * 添加好友
     * @param string $userTxCode
     * @param string $friendTxCode
     * @return bool
     *
     */
    public function addFriend($userTxCode = '',  $friendTxCode = '') {
        if (!$userTxCode || !$friendTxCode) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/sns/friend_add?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";


        // 封装参数
        $data = [
            'From_Account' => $userTxCode,   #1：把消息同步到 From_Account 在线终端和漫游上 2：消息不同步至 From_Account；若不填写默认情况下会将消息存 From_Account 漫游
            'AddFriendItem' => [
                [
                    'To_Account' => $friendTxCode,
                    'AddSource' => "AddSource_Type_XXXXXXXX",
                ],
            ],
            "ForceAddFlags" => 1,   #管理员强制加好友标记：1表示强制加好友，0表示常规加好友方式
            'AddType' => "Add_Type_Both",  # Add_Type_Single 表示单向加好友    Add_Type_Both 表示双向加好友
        ];

//        Yii::info(json_encode($data,true),'IM请求信息');
        //发送请求
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 修改好友信息(备注)
     * @param string $userTxCode
     * @param string $friendTxCode
     * @param array $updateData
     * @return bool
     *
     */
//    public function updateFriend($userTxCode = '',  $friendTxCode = '', $mark = '') {
    public function updateFriend($userTxCode = '',  $friendTxCode = '', $updateData = []) {
        if (!$userTxCode || !$friendTxCode || !$updateData) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/sns/friend_update?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";


        // 封装参数
        $data = [
            'From_Account' => $userTxCode,   #需要更新该 UserID 的关系链数据
            'UpdateItem' => [
                [
                    'To_Account' => $friendTxCode,
//                    "SnsItem" =>
//                        [
//                            [
//                                'Tag' => 'Tag_SNS_IM_Remark',
//                                'Value' => $mark,
//                            ],
//                        ],
                    "SnsItem" => $updateData,
                ],
            ],
        ];
        //发送请求
//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 删除好友
     * @param string $userTxCode
     * @param string $friendTxCode
     * @return bool
     *
     */
    public function deleteFriend($userTxCode = '',  $friendTxCode = '') {
        if (!$userTxCode || !$friendTxCode) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/sns/friend_delete?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";


        // 封装参数
        $data = [
            'From_Account' => $userTxCode,   # 需要删除该 UserID 的好友
            'To_Account' => [
                $friendTxCode,
            ],   #待删除的好友的 UserID 列表，单次请求的 To_Account 数不得超过1000
            'DeleteType' => "Delete_Type_Both", # 双向删除好友
        ];

        //发送请求
//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }


    /**
     * 获取好友信息
     * @param string $userTxCode
     * @param string $friendTxCode
     * @return bool
     *
     */
    public function getFriend($userTxCode = '',  $friendTxCode = '') {
        if (!$userTxCode || !$friendTxCode) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/sns/friend_get_list?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";


        // 封装参数
        $data = [
            'From_Account' => $userTxCode,
            'To_Account' => [
                $friendTxCode,
            ],   #待删除的好友的 UserID 列表，单次请求的 To_Account 数不得超过1000
            #指定要拉取的资料字段及好友字段
            "TagList" =>
                [
                    "Tag_Profile_IM_Image",
                    "Tag_Profile_IM_Nick",
                    "Tag_SNS_IM_Remark",
                    "Tag_SNS_IM_Group",
                    "Tag_SNS_Custom_iscircle"
                ]
        ];

        //发送请求
//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 创建群组
     * @param string $groupTxCode
     * @param string $userTxCode
     * @param string $groupName
     * @param string $groupFace
     * @param string $notice
     * @param array $groupUser
     * @param array $defineData
     * @return bool
     */
    public function addGroup($groupTxCode = '', $userTxCode = '', $groupName = '', $groupFace  = '', $notice = '', $groupUser = [], $defineData = []) {
        if (!$groupTxCode || !$userTxCode) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
//        Yii::info($signStr,'获取签名');
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'Owner_Account' => (string) $userTxCode,
            'Type' => "Public",
            'GroupId' => (string) $groupTxCode,
            'Name' => (string) $groupName,
            'FaceUrl' => (string) $groupFace,
            'Notification' => (string) $notice,
            'Introduction' => (string) $groupTxCode . ',' .$userTxCode,
            'MaxMemberCount' => 2000,
            "MemberList" => $groupUser,
        ];

        if ($defineData) {
            $data['AppDefinedData'] = $defineData;
        }

//        Yii::info(json_encode($data,true),'IM请求信息');

        $curl = new Curl();
        $curl->setPostParams(json_encode($data,true));
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 添加群成员
     * @param string $groupTxCode
     * @param array $groupUser
     * @return bool
     */
    public function addGroupMember($groupTxCode = '', $groupUser = []) {
        if (!$groupTxCode || !$groupUser) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/add_group_member?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'GroupId' => (string) $groupTxCode,
//            'Silence' => (int) 1,
            "MemberList" => $groupUser,
        ];

//        Yii::info(json_encode($data,true),'IM请求信息');

        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }

        if ($res['MemberList']) {
            foreach ($res['MemberList'] as $key => $value) {
                if ($value['Result'] != 1) {
                    continue;
                }


                foreach ($groupUser as $kk => $vv) {
                    if ($vv['Member_Account'] == $value['Member_Account']) {
                        if (isset($vv['AppMemberDefinedData'])) {
                            $updateGroupUserData['GroupId'] = $groupTxCode;
                            $updateGroupUserData['Member_Account'] = $value['Member_Account'];
                            $updateGroupUserData['AppMemberDefinedData'] = $vv['AppMemberDefinedData'];
                            $this->updateGroupUser($updateGroupUserData);
                        }

                    }
                }
            }
        }

        return true;
    }

    /**
     *  获取im群信息
     * @param string $groupTxCode
     * @return array|bool
     */
    public function getGroupInfo($groupTxCode = '') {
        if (!$groupTxCode) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_info?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'GroupIdList' => [
                (string) $groupTxCode,
            ],
            "ResponseFilter" => [
                "GroupBaseInfoFilter" => [
                    'MemberNum',
                    'MaxMemberNum',
                ],
                "AppDefinedDataFilter_Group" => [
                    "tx_code"
                ],
            ],
        ];

//        Yii::info(json_encode($data,true),'IM请求信息');

        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        $result = [
            'MaxMemberNum' => 0,
            'MemberNum' => 0,
        ];
        if ($res['ErrorCode'] != 0) {
            return $result;
        }

        if (isset($res['GroupInfo']) && !empty($res['GroupInfo'])) {
            $groupInfo = $res['GroupInfo'][0];
            $result = [
                'MaxMemberNum' => $groupInfo["MaxMemberNum"],
                'MemberNum' => $groupInfo["MemberNum"],
            ];
        }

        return $result;
    }

    /**
     * 更新群信息
     * @param array $updateGroupData
     * @return bool
     */
    public function updateGroup($updateGroupData = []) {
        if (!$updateGroupData) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
//        Yii::info($signStr,'获取签名');
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = $updateGroupData;

        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 转让群
     * @param string $groupTxCode
     * @param string $userTxCode
     * @return bool
     */
    public function transGroup($groupTxCode = '', $userTxCode) {
        if (!$groupTxCode) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
//        Yii::info($signStr,'获取签名');
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/change_group_owner?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'GroupId' => $groupTxCode,
            'NewOwner_Account' => $userTxCode,
        ];

//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 解散群
     * @param string $groupTxCode
     * @return bool
     */
    public function delGroup($groupTxCode = '') {
        if (!$groupTxCode) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'GroupId' => $groupTxCode,
        ];

//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }


    /**
     * 更新群成员信息
     * @param array $updateGroupUserData
     * @return bool
     */
    public function updateGroupUser($updateGroupUserData = []) {
        if (!$updateGroupUserData) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
//        Yii::info($signStr,'获取签名');
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_member_info?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = $updateGroupUserData;

//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 群成员禁言
     * @param array $updateGroupUserData
     * @return bool
     */
    public function shutUpGroupUser($updateGroupUserData = []) {
        if (!$updateGroupUserData) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
//        Yii::info($signStr,'获取签名');
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/forbid_send_msg?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = $updateGroupUserData;

//        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 删除群成员
     * @param array $delGroupUserData
     * @return bool
     */
    public function delGroupUser($delGroupUserData = []) {
        if (!$delGroupUserData) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/delete_group_member?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = $delGroupUserData;

        Yii::info(json_encode($data,true),'IM请求信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));

        $res = $curl->post($url);
        $res = json_decode($res, true);
        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     *  发送单聊文本消息
     * @param string $receiveUserCode
     * @param array $info
     * @param string $sendUserCode
     * @return bool
     */
    public function sendUserMessageText($receiveUserCode = '', $info = [], $sendUserCode = '') {
        if (!$receiveUserCode || !$info) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 发送文本消息
        $data = [
            'SyncOtherMachine' => (int) 1,   #1：把消息同步到 From_Account 在线终端和漫游上 2：消息不同步至 From_Account；若不填写默认情况下会将消息存 From_Account 漫游
            'To_Account' => $receiveUserCode,    #消息接收方用户 UserID 一次请求最多500次
            'MsgRandom' => (int) Functions::generateCode(6),
            "MsgTimeStamp" => time(),
            'MsgBody' => [
                [
                    'MsgType' => 'TIMTextElem',
                    'MsgContent' => [
                        'Text' => is_array($info) ? json_encode($info) : $info,
                    ],
                ],
            ],
        ];

        if ($sendUserCode) {
            $data['From_Account'] = $sendUserCode;
        }
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     *  发送单聊自定义消息
     * @param string $receiveUserCode
     * @param array $info
     * @param string $sendUserCode
     * @return bool
     */
    public function sendUserSingleMessage($receiveUserCode = '', $info = [], $sendUserCode = '') {
        if (!$receiveUserCode || !$info) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 发送文本消息
        $data = [
            'SyncOtherMachine' => (int) 1,   #1：把消息同步到 From_Account 在线终端和漫游上 2：消息不同步至 From_Account；若不填写默认情况下会将消息存 From_Account 漫游
            'To_Account' => $receiveUserCode,    #消息接收方用户 UserID 一次请求最多500次
            'MsgRandom' => (int) Functions::generateCode(6),
            "MsgTimeStamp" => time(),
            'MsgBody' => [
                [
                    'MsgType' => 'TIMCustomElem',
                    'MsgContent' => $info,
                ],
            ],
        ];

        if ($sendUserCode) {
            $data['From_Account'] = $sendUserCode;
        }

//        Yii::info(json_encode($data,true),'IM发送信息');

        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 群组中发送单个消息 - 自定义消息
     * @param string $groupId
     * @param array $msgContent
     * @param string $fromAccount
     * @return bool
     */
    public function sendGroupSingleMessage($groupId = '', $msgContent = [], $fromAccount = '') {
        if (!$groupId || !$msgContent) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'GroupId' => (string) $groupId,
//            'From_Account' => (string) $fromAccount,
            'Random' => (int) Functions::generateCode(6),
            'MsgBody' => [
                [
                    'MsgType' => 'TIMCustomElem',
                    'MsgContent' => $msgContent,
                ],
            ],
        ];


        if ($fromAccount) {
            $data['From_Account'] = $fromAccount;
        }

        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 群组中发送系统消息 - 自定义消息
     * @param string $groupId
     * @param string $msgContent
     * @param array $toAccount
     * @return bool
     */
    public function sendGroupSingleSystemMessage($groupId = '', $msgContent = '', $toAccount = []) {
        if (!$groupId || !$msgContent || !$toAccount) {
            return false;
        }
        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        $data = [
            'GroupId' => (string) $groupId,
            'ToMembers_Account' => [
                $toAccount
            ],
            'Content' => $msgContent,
        ];


        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
//        Yii::info(json_encode($data,true),'IM发送信息');

        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }


    /**
     * 批量发送单聊信息
     * @param array $receiveUserCode
     * @param $msgContent
     * @param string $sendUserCode
     * @return bool
     */
    public function singleUserSendBatchMsg($receiveUserCode = [], $msgContent, $sendUserCode = '') {
        if (!$receiveUserCode || !$msgContent) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/openim/batchsendmsg?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 发送文本消息
        $data = [
            'SyncOtherMachine' => (int) 1,   #1：把消息同步到 From_Account 在线终端和漫游上 2：消息不同步至 From_Account；若不填写默认情况下会将消息存 From_Account 漫游
            'To_Account' => $receiveUserCode,    #消息接收方用户 UserID 一次请求最多500次
            'MsgRandom' => (int) Functions::generateCode(6),
            "MsgTimeStamp" => time(),
            'MsgBody' => [
                [
                    'MsgType' => 'TIMCustomElem',
                    'MsgContent' => $msgContent,
                ],
            ],
        ];

        if ($sendUserCode) {
            $data['From_Account'] = $sendUserCode;
        }

//        Yii::info($data,'IM发送信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }


    /**
     * 查询在线状态
     * @param array $userTxCode
     * @return array|bool
     */
    public function queryOnlineStatus($userTxCode = []) {
        if (!$userTxCode) {
            return false;
        }

        $result = [];

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/openim/query_online_status?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 发送文本消息
        $data = [
            'To_Account' => $userTxCode,   #用户名
        ];

//        Yii::info($data,'IM发送信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return $result;
        }
        $result = $res['QueryResult'];
        return $result;
    }

    /**
     * 登录失效
     * @param string $userTxCode
     * @return bool
     */
    public function loginOut($userTxCode = '') {
        if (!$userTxCode) {
            return false;
        }

        // 获取签名
        $signStr = $this->imSignatureGeneration();
        $url = "https://console.tim.qq.com/v4/im_open_login_svc/kick?sdkappid=" . $this->SDKAPPID . "&identifier=" . $this->USER_ID . "&usersig=" . $signStr . "&random=99999999&contenttype=json";

        // 发送文本消息
        $data = [
            'UserID' => (string) $userTxCode,   #用户名
        ];

//        Yii::info($data,'IM发送信息');
        $curl = new Curl();
        $curl->setRawPostData(json_encode($data,true));
        $res = $curl->post($url);
        $res = json_decode($res, true);
//        Yii::info($res,'IM信息');
        if ($res['ErrorCode'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 签名生成
     * @param string $userId
     * @param int $expire
     * @return string
     */
    public function imSignatureGeneration($userId = '', $expire = 0) {
        $model = new TLSSigAPIv2($this->SDKAPPID, $this->KEY);
        $userId = $userId ? $userId : $this->USER_ID;
        $expire = $expire ? $expire : 3600;
        $sigStr = $model ->genUserSig($userId,$expire);
//        var_dump($sigStr);die;
        return $sigStr;
    }



}